/*
 * @Description: 分货调整明细页面
 * @Version: 1.0
 * @Autor: c-jack.qian
 * @Date: 2020-10-21 17:30:52
 * @LastEditors: c-jack.qian
 * @LastEditTime: 2021-04-25 11:55:49
 */
import React, { useEffect, useState } from 'react';
import { PageHeaderWrapper } from 'hzero-boot/lib/components/Page';
import {
  Button,
  DataSet,
  Form,
  MonthPicker,
  notification,
  Select,
  TextField,
} from 'choerodon-ui/pro';
import { ButtonColor } from 'choerodon-ui/pro/lib/button/enum';
import { useDataSet, useDataSetEvent } from 'hzero-front/lib/utils/hooks';
import { DataSetProps } from 'choerodon-ui/pro/lib/data-set/DataSet';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import querystring from 'querystring';
import intl from 'utils/intl';
import {
  orderDistributionDtlFormDS,
  orderDistributionDtlTableDS,
  approvalDS,
  // submitDateSet,
} from '../../stores/orderDistributionDtlDS';
import ProductTable from './component/productTable';
import ApprovalTable from './component/approvalTable';

notification.config({
  duration: 3,
  placement: 'bottomRight',
});
interface propstype {
  dispatch: any;
  match: any;
  location: any;
}

const ClassPage: React.FC<propstype> = ({ dispatch, location }) => {
  const tableDS = useDataSet(() => new DataSet(orderDistributionDtlTableDS() as DataSetProps));
  const formDS = useDataSet(() => new DataSet(orderDistributionDtlFormDS() as DataSetProps));
  const approvalDateSet = useDataSet(() => new DataSet(approvalDS() as DataSetProps));
  // const submitDS = useDataSet(() => new DataSet(submitDateSet() as DataSetProps));
  const [areaDisable, setAreaDisable] = useState(false);

  const { search } = location;
  const queryStr: any = new URLSearchParams(search).get('params');
  const urlParamsObj = JSON.parse(decodeURIComponent(queryStr));

  useEffect(() => {
    if (urlParamsObj && urlParamsObj.id) {
      setAreaDisable(true);
      reqDetailData(urlParamsObj.id);
    }else{
      tableDS.loadData([])
      formDS.removeAll();
      formDS.create({}, 0);
    }
  }, [location.search]);

  // 根据大区来来查小区
  useDataSetEvent(formDS, 'update', ({ dataSet, name }) => {
    if (name === 'regionId') {
      dataSet.current.set('areaId', null);
      const areaField = dataSet.getField('areaId');
      if (!dataSet.current.get('regionId')) {
        areaField.set('disabled', true);
      } else {
        areaField.set('disabled', false);
      }
    }
  });

  //请求详情id
  const reqDetailData = async id => {
    formDS.setQueryParameter('quotaOrderDetailId', Number(id));
    // 请求详情
    await formDS.query();
    tableDS.setQueryParameter('quotaOrderId', Number(id));
    tableDS.query().then(resList => {
      console.log('resList', resList);
      const { content } = resList;
      if (content.length) {
        // 设置订单编号lov查询条件
        const areaId = formDS.current?.get('areaId');
        const orderObjField = tableDS.getField('orderObj');
        orderObjField?.setLovPara('areaId', areaId);
      }
    });
  };

  // 封装，明细列表上传数据
  const lineSubmitData = () => {
    let djiQuotaOrderDetailList: any = [];
    const tableList = tableDS.toData();
    if (tableList) {
      djiQuotaOrderDetailList = tableList.map((item: any) => {
        delete item.orderObj;
        return {
          ...item,
        };
      });
    }
    return djiQuotaOrderDetailList;
  };

  const handleSave = () => {
    handleSubmitorSave('save');
  };

  const handleSubmit = () => {
    handleSubmitorSave('submit');
  };

  const handleSubmitorSave = async type => {
    const validate = await tableDS.validate();
    if (!validate) {
      notification.warning({
        placement: 'bottomRight',
        message: intl.get(`dji.otc.om.view.reminder.warning`).d('提示'),
        description: intl.get('dji.otc.om.view.remind.orderDistributionDetailLineRequire').d('分货行明细必填项未填写！！'),
      });
      return;
    }

    const lineData = lineSubmitData();
    if (!lineData.length) {
      notification.warning({
        placement: 'bottomRight',
        message: intl.get(`dji.otc.om.view.reminder.warning`).d('提示'),
        description: intl.get('dji.otc.om.view.remind.orderDistributionRequire').d('分货明细未填写！！'),
      });
      return;
    }
    formDS.current?.set('djiQuotaOrderDetailList', lineData);
    formDS.current?.set('type', type);
    formDS.submit().then(res => {
      if (res) {
        const id =
          urlParamsObj && urlParamsObj.id
            ? urlParamsObj.id
            : res.content && res.content[0].quotaOrderId;
        dispatch(
          routerRedux.push({
            pathname: `/o2om/order-distribution/create`,
            search: querystring.stringify({
              params: encodeURIComponent(JSON.stringify({ id, number: Math.random() })),
            }),
          })
        );
        // reqDetailData(id);
        setAreaDisable(true);
      }
    });
  };

  const optionsFilter = record => {
    const regionId = formDS.current?.get('regionId');
    const parentCodeValue = record.get('parentCodeValue');
    return regionId ? Number(regionId) === parentCodeValue : true;
  };

  return (
    <PageHeaderWrapper
      title={
        urlParamsObj
          ? intl.get('dji.otc.om.view.menu.editOrderDistribution').d('编辑订单分货')
          : intl.get('dji.otc.om.view.menu.createOrderDistribution').d('新建订单分货')
      }
      header={
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Button icon="save" key="import" onClick={() => handleSave()}>
            {intl.get(`dji.otc.om.view.button.save`).d('保存')}
          </Button>
          <Button key="submit" onClick={() => handleSubmit()} color={ButtonColor.primary}>
            {intl.get(`dji.otc.om.view.button.submit`).d('提交')}
          </Button>
        </div>
      }
    >
      <Form dataSet={formDS} columns={2}> 
        <TextField name="quotaCode" placeholder={intl.get('dji.otc.om.view.field.generatedByTheSystem').d("系统自动生成")} disabled />
        {/* <Lov name="productObj" /> */}
        <Select name="regionId" disabled={areaDisable} />
        <Select name="areaId" optionsFilter={optionsFilter} disabled={areaDisable} />
        <Select name="customerType" />
        <MonthPicker name="quotaMonth" />
        <Select name="businessGroup" />
      </Form>
      <ProductTable tableDS={tableDS} dispatch={dispatch} parentDS={formDS} />
      {/* 审批记录 */}
      <ApprovalTable tableDS={approvalDateSet} />
    </PageHeaderWrapper>
  );
};

export default connect()(ClassPage);
